$(document).ready(function() {
	showAlert();
	prepareCallServiceMovies();
});

function showAlert() {
	alert('La pagina esta cargada');
	$('#alias').focus();
}

function prepareCallServiceHello() {
	$('#send').click(function() {
		callServiceHello($('#alias').val());
	});
}
function callServiceHello(alias) {
	$.post("api/dispatcher.php",{ 
		service: "welcome.hello", 
		params: {"name": alias} 
	}).done(function(data) { 
		$("#response").html(data);
		
		$("#response").removeClass('error');
		$("#response").addClass("transparent");
		
		if (data.indexOf(alias) > 0) {
			$("#response").highlight(alias);
		}
	}).fail(function(jqXHR, textStatus, errorThrown) { 
		$("#response").html(textStatus + errorThrown);
		
		$("#response").removeClass('transparent');
		$("#response").addClass("error");
	});
}


function prepareCallServiceMovies() {
	$('#send').click(function() {
		$.mobile.showPageLoadingMsg();
		callServiceMovies($('#alias').val());
	});
}
function callServiceMovies(alias) {
	$.getJSON("api/dispatcher.php",{ 
		service: "movie.getTop",
		params: {"name": alias} 		
	}).done(function(data) { 		
		createRows(data);
		
		$("#response").removeClass('error');
		$("#response").addClass("transparent");
		$.mobile.hidePageLoadingMsg();
	}).error(function(jqXHR, textStatus, errorThrown) { 
		$("#response").html(textStatus + errorThrown);
		
		$("#response").removeClass('transparent');
		$("#response").addClass("error");
		$.mobile.hidePageLoadingMsg();
	});

}


function createRows(data) {
	var htmlStr = '';
	$.each(data, function(key, value) {
		htmlStr = htmlStr.concat("<li>");
		htmlStr = htmlStr.concat("<img src='").concat(data[key].BoxArt.SmallUrl).concat("'/>");
		
		htmlStr = htmlStr.concat("<label><a href='#dialogDetail' data-rel='dialog' data-transition='pop' ");
		htmlStr = htmlStr.concat("onClick='openDialogDetail(" + data[key].Name + ")'>");
		htmlStr = htmlStr.concat(data[key].Name).concat("</a></label><br/>");
		
		htmlStr = htmlStr.concat("<label>Release Year: ").concat(data[key].ReleaseYear).concat("</label><br/>");
		htmlStr = htmlStr.concat("<label>Short Synopsis: ").concat(data[key].ShortSynopsis).concat("</label>");
		htmlStr = htmlStr.concat("</li>");
	});
	$("#movies").html(htmlStr);
	$("#movies").listview('refresh');
}

function openDialogDetail(name){     
	alert(name);
	$("#releaseYear").html(name);	
}